// TypeScript file
declare function hex_md5(msg:string);
class http {
    // private static loginUrl = 'http://192.168.1.132:8010/HomeApi/';//登录公共库
    // private static loginUrl = 'http://120.27.128.91:86/HomeApi/';
    private static loginUrl = 'https://h5-api.farm.pk0818.com:8443/HomeApi/';
    private static appKey = 'homeApi';
    private static appSign = '6f0ae19125d5942eef871227308d4881';
    private static ajaxSignstr(ajaxValues){
        ajaxValues.app_key = http.appKey;
        var reStr = '';
        var returnValues = {};
        var keyArr = [];
        var i = 0;
        var reStr = "";
        for (var info in ajaxValues) {
            keyArr[i] = info;
            i++;
        }
        keyArr = keyArr.sort();
        for (var index in keyArr) {
            if(ajaxValues[keyArr[index]] != undefined && ajaxValues[keyArr[index]] != 'undefined'){
                if(ajaxValues[keyArr[index]] instanceof Array){
                    reStr = reStr +  keyArr[index] + '=' + http.ajaxUrlEncode(JSON.stringify(ajaxValues[keyArr[index]])) + '&';
                }else{
                    reStr = reStr + keyArr[index] + '=' + http.ajaxUrlEncode(ajaxValues[keyArr[index]]) + '&';
                }
            }
        }
        reStr = reStr.substring(0, reStr.length - 1);
        reStr = reStr + "&sign=" + hex_md5(reStr + http.appSign)
        return reStr;
    }
    private static ajaxUrlEncode = function(string) {
        string = string + '';
        string = encodeURIComponent(string);
        string = string.replace(/%20/g, '+');
        var asciiStr = "~'";
        var encodeStr = '%7e%27';
        for (var i = 0; i < asciiStr.length; i++) {
            var replaceStr = asciiStr.substr(i, 1);
            var changeStr = encodeStr.substr(i * 3, 3);
            string = string.replace(new RegExp(replaceStr, 'g'), changeStr);
        }
        return string;
    }
    public static async getHttpServer(config,dataPost:any = {},note:any = -1){
        var values:any = {};
        var url = "";
        url = this.loginUrl+common.configUrl[config];
        switch(config){
            case "login":{
                url = this.loginUrl+common.configUrl[config];
                values["code"] = analysis.hrefValue("code");
                values["areaId"] = analysis.hrefValue("areaId");
                common.areaId = parseInt(values["areaId"]);
                values["gameId"] = analysis.hrefValue("gameId");
                common.gameId = parseInt(values["gameId"]);
                values["invite"] = analysis.hrefValue("invite");
                values["sId"] = localStorage.getItem("sId") ? localStorage.getItem("sId") : "";
                break;
            }
            case "createOrder":{
                values = dataPost;
                break;
            }
            case "logisticsInfo":{
                values = dataPost;
                break;
            }
            case "wxConfig":{
                values = {
                    "areaId":common.areaId,
                    "userId":common.userInfo.userId,
                    "gameId":common.gameId,
                    "url":location.href.split('#')[0]
                }
                break;
            }
        }
        var params = this.ajaxSignstr(values);
        var request = new egret.HttpRequest();
        request.responseType = egret.HttpResponseType.TEXT;
        //设置为 POST 请求
        request.open(url,egret.HttpMethod.POST);
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        request.send(params);
        request.addEventListener(egret.Event.COMPLETE,(event)=>{
            let request = <egret.HttpRequest>event.currentTarget;
            switch(config){
                case "login":{
                    let response =JSON.parse(request.response);
                    let data = response.data;
                    if(response.code !== 0){
                        alert("用户登录信息缺失，请重新登录");
                        location.href = "http://wechat.17pkmj.com/h5code?gameid=2001";
                        return;
                    }
                    localStorage.setItem("sId",data.sId);
                    common.userInfo.head = data.head;
                    common.userInfo.nickName = data.nickname;
                    common.userInfo.sex = data.sex;
                    common.userInfo.numId = data.numId;
                    common.userInfo.userId = data.userId;
                    common.userInfo.exp = data.exp;
                    common.userInfo.maxExp = data.maxExp;
                    common.userInfo.lv = data.lv;
                    common.userInfo.title = data.name;
                    common.userInfo.energy = data.energy;
                    common.userInfo.petId = data.petId;
                    common.userInfo.petStatus = data.petStatus;
                    if(data.newUser){
                        common.userInfo.login = 0;
                    }
                    if(data.nowFirstLogin){
                        common.userInfo.today = 0;
                    }
                    socket.coonect();
                    break;
                }
                case "createOrder":{
                    let response = JSON.parse(request.response);
                    let data = response.data;
                    if(response.code !== 0){
                        return;
                    }
                    Dispatcher.ins.dispatchEvent(new GameEvent("createOrder",{"data":data,"note":note}));
                    break;
                }
                case "logisticsInfo":{
                    let response = JSON.parse(request.response.substr(0,request.response.length - 1));
                    if(response.message !== "ok") return;
                    Dispatcher.ins.dispatchEvent(new GameEvent("logisticsInfo",response));
                    break;
                }
                case "wxConfig":{
                    let response = JSON.parse(request.response);
                    let data = response.data;
                    if(response.code !== 0){
                        return;
                    }
                    Dispatcher.ins.dispatchEvent(new GameEvent("wxConfig",data));
                    break;
                }
            }
        },this);
        request.addEventListener(egret.IOErrorEvent.IO_ERROR,this.onIOError,this);
        request.addEventListener(egret.ProgressEvent.PROGRESS,this.onProgress,this);
    }
    private static onComplete(config,event:egret.Event):void {
        var request = <egret.HttpRequest>event.currentTarget;
        var response = JSON.parse(request.response);
    }
    private static onIOError(event:egret.IOErrorEvent):void {
        console.log("get error : " + event);
    }
    private static onProgress(event:egret.ProgressEvent):void {
        console.log("get progress : " + Math.floor(100*event.bytesLoaded/event.bytesTotal) + "%");
    }
}